/*
 * node.c
 *
 *  Created on: May 21, 2012
 *      Author: burek
 */

#include "node.h"
#include "location.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

// Konstrukcija noda iz stringa kakav se salje preko mreze
// intAddr:port:location
CNode * cn_constructNode(const char * repLine)
{
	char *semi1, *semi2;
	char buff[512];
	char addrTemp[512];
	CNode *node = NULL;
	int len = strlen(repLine);
	unsigned int a = 0;

	semi1 = strchr(repLine, ':');
	if(semi1 == NULL)
		return NULL;

	semi2 = strchr(semi1 + 1, ':');
	if(semi2 == NULL)
		return NULL;

	node = (CNode*)calloc(1, sizeof(CNode));

	strncpy(buff, repLine, semi1 - repLine);
	buff[semi1 - repLine] = '\0';
	sscanf(buff, "%u", &(node->addrInt));

	strncpy(buff, semi1 + 1, semi2 - semi1);
	sscanf(buff, "%d", &(node->port));

	node->location = (char*)malloc((repLine + len) - semi2 + 1);
	strncpy(addrTemp, semi2 + 1, (repLine + len) - semi2);

	cl_reverseAddress(addrTemp, node->location);

	node->addrText = (char*)malloc(16);
	a = node->addrInt;
	if(a == 0)
	{
		puts("lolwut? zero address?");
	}
	sprintf(node->addrText, "%d.%d.%d.%d", a & 0xFF, (a >> 8) & 0xFF, (a >> 16) & 0xFF, (a >> 24) & 0xFF);

	return node;
}

void cn_printNode(const CNode * node)
{
	if(node == NULL)
	{
		printf("{NULL Node}\n");
	}
	else
	{
		printf("{Node}\n");
		printf("Address (int): %u\n", node->addrInt);
		printf("Address (txt): %s\n", node->addrText);
		printf("Port         : %d\n", node->port);
		printf("Location     : %s\n\n", node->location);
	}
	fflush(stdout);
}

// Oslobadjanje memorije
void cn_destroyNode(CNode * node)
{
	if(node == NULL) return;
	if(node->addrText) free(node->addrText);
	if(node->location) free(node->location);
	free(node);
}
